package com.musemun.config.handler;

import com.alibaba.fastjson.JSON;
import com.musemun.common.CommonResult;
import com.musemun.contants.ReturnType;
import com.musemun.pojo.Employee;

import com.musemun.pojo.EmployeeRepository;
import com.musemun.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    Logger logger= LoggerFactory.getLogger(LogoutSuccessHandler.class);
    @Resource
    private EmployeeRepository employeeRepository;


    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        String username = JwtTokenUtil.getUsernameFromToken(httpServletRequest.getHeader("token"));
        Employee employee = employeeRepository.remove(username);
        logger.info("用户注销成功");
        ReturnType.returnJson(httpServletResponse);
        if (employee!=null){
            httpServletResponse.getWriter().write(JSON.toJSONString(new CommonResult<String>(200, employee.getEName()+"用户注销成功")));
        }
       else{
            httpServletResponse.getWriter().write(JSON.toJSONString(new CommonResult<String>(500, "无效的token")));
        }
        httpServletResponse.flushBuffer();
    }
}
